package com.czl.module_work.fragment

import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.module_work.BR
import com.czl.module_work.R
import com.czl.module_work.databinding.WorkFragmentScanBinding
import com.czl.module_work.viewModel.ScanViewModel
import android.content.Context.VIBRATOR_SERVICE

import android.os.Vibrator
import android.text.TextUtils
import com.blankj.utilcode.util.ToastUtils
import com.czl.base.event.LiveBusCenter
import com.czl.base.util.core.QRCodeView


/**
 * 创建日期：2022/1/18  17:38
 * 类说明:
 * @author：86152
 */
@Route(path = AppConstants.Router.Work.F_WORK_SCAN)
class ScanFragment :
    BaseFragment<WorkFragmentScanBinding, ScanViewModel>(), QRCodeView.Delegate {

    override fun useBaseLayout(): Boolean = false;

    override fun initContentView(): Int = R.layout.work_fragment_scan

    override fun initVariableId(): Int = BR.viewModel

    override fun initData() {
        viewModel.tvTitle.set("扫码")
        binding.zxingview.setDelegate(this)
    }

    override fun onStart() {
        super.onStart()
        binding.zxingview.startCamera()
        binding.zxingview.changeToScanQRCodeStyle()
        //开始扫描
        binding.zxingview.showScanRect()
        binding.zxingview.startSpot()
    }

    override fun onStop() {
        binding.zxingview.stopCamera()
        super.onStop()
    }

    override fun onDestroy() {
        binding.zxingview.onDestroy()
        super.onDestroy()
    }

    private fun vibrate() {
        val vibrator = context?.getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }


    override fun onScanQRCodeSuccess(result: String?) {
        vibrate();
        if(!TextUtils.isEmpty(result)) {
            viewModel.finish()
            LiveBusCenter.postScanResultEvent(result ?: "")
        }
        binding.zxingview.stopCamera();
    }

    override fun onScanQRCodeOpenCameraError() {

    }

}